package cn.net.sichen.server.controller;

import cn.net.sichen.server.db.MockDB;
import cn.net.sichen.server.entity.ClientInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class SsoServerController {

    @RequestMapping("/index")
    public String index(){
        return "login";
    }


    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response,
                        String username, String password, String redirectUrl, Model model) {

        if ("admin".equals(username) && "123456".equals(password)) {
            // 生成token
            String token = UUID.randomUUID().toString();

            MockDB.T_TOKEN.add(token);

            model.addAttribute("token", token);

            request.getSession().setAttribute("token", token);

            return "redirect:" + redirectUrl;
        }
        model.addAttribute("redirectUrl", redirectUrl);
        return "login";
    }


    @RequestMapping("/checkLogin")
    public String checkLogin(HttpServletRequest request, HttpServletResponse response,
                             String redirectUrl, Model model){

        String token = (String) request.getSession().getAttribute("token");

        if (StringUtils.isEmpty(token)) {
            model.addAttribute("redirectUrl",redirectUrl);
            return "login";
        } else {
            // 已登录
            model.addAttribute("token",token);
            return "redirect:" + redirectUrl;
        }
    }

    @RequestMapping("/verify")
    @ResponseBody
    public String verify(String token,String clientUrl, String jsessionId){

        if (MockDB.T_TOKEN.contains(token)) {
            List<ClientInfo> clientInfos = MockDB.T_CLIENT_INFO.get(token);

            if (clientInfos == null) {
                clientInfos = new ArrayList<ClientInfo>();
                MockDB.T_CLIENT_INFO.put(token, clientInfos);
            }

            ClientInfo clientInfo = new ClientInfo();
            clientInfo.setClientUrl(clientUrl);
            clientInfo.setJsessionid(jsessionId);

            clientInfos.add(clientInfo);

            // 验证通过
            return "true";
        }
        return "false";
    }


    @RequestMapping("/logOut")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
}
